//
//  AllCommentViewController.m
//  唧歪
//
//  Created by ZC on 15/7/15.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "AllCommentViewController.h"
#import "AppDelegate.h"
#import "commCell.h"
#import "Comment.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ImageCompression.h"

#define allCommentURL @"https://app.jiwaipro.com:8888/index.php/JiWai/allcomment"  //全部评论
#define commentImageURL @"https://app.jiwaipro.com:8888/index.php/JiWai/uploadCommentImage"  //图片评论url
#define commentURL @"https://app.jiwaipro.com:8888/index.php/JiWai/comment"  //评论请求
#define addTimeURL @"https://app.jiwaipro.com:8888/index.php/JiWai/postaddtime"  //显示时间加1
#define commentcountURL @"https://app.jiwaipro.com:8888/index.php/JiWai/addtimeandcount"  //评论数和显示时间url
#define dxcommentURL @"https://app.jiwaipro.com:8888/index.php/JiWai/dxcomment" //评论正倒序
#define audioURL @"https://app.jiwaipro.com:8888/index.php/JiWai/uploadcommentaudio"

@interface AllCommentViewController (){
    NSString *strIdentifier;
    NSString *strIdentifier1;
    NSMutableArray *allCommentArray;
    NSMutableArray *commentstr;
    NSMutableArray *commentArray2;
    NSMutableArray *DX_allCommentArray;
    NSMutableArray *DX_Array;
    AppDelegate *app;
    UIImage *img;
    NSString *Content;
    NSString *commentID;
    UIAlertView *_alert;
    NSString *currentTime;
    NSString *contentStr;
    NSString *commcount;
    Comment *c;
    NSString *showTimeStr;
    NSString *str;
    int keyboard;
    commCell *cell;
    NSString *dxstr;
    int pageNumber;
    int DX_pageNumber;
    int DX_int;
    NSString *newviewStr;
    NSURL *recordUrl;
    NSString *cellContent;
    NSIndexPath *indexP;
    
}

@end

@implementation AllCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    strIdentifier1 = @"0";
    DX_Array = [NSMutableArray array];
    DX_allCommentArray = [NSMutableArray array];
    allCommentArray = [NSMutableArray array];
    commentstr = [NSMutableArray array];
    commentArray2 = [NSMutableArray array];
    app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    //键盘通知
    [[ NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeContentViewPoint:)name: UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    self.recordView.backgroundColor = [UIColor redColor];
    self.recordView = [[FXRecordArcView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
    self.recordView.delegate = self;
    self.recordView.hidden = YES;
    self.recordView.delegate = self;
    [self.helddownButton setTitle:@"按住说话" forState:UIControlStateNormal];
    [self.helddownButton addTarget:self action:@selector(btnDown) forControlEvents:UIControlEventTouchDown];
    [self.helddownButton addTarget:self action:@selector(LongPress) forControlEvents:UIControlEventTouchUpInside];
    [self.helddownButton.layer setMasksToBounds:YES];
    [self.helddownButton.layer setCornerRadius:7.0];
    
    self.textFeild.delegate =self;
    //return键改成Done键
    self.textFeild.returnKeyType =UIReturnKeyDone;
    
    pageNumber = 1;
    DX_pageNumber = 1;
    DX_int = 0;
    
    self.tableView.footer = [[KSDefaultFootRefreshView alloc] initWithDelegate:self]; //上拉刷新
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
        [self addData];
        app.Existence = @"0";
    }
}
-(void)btnDown
{
    [self.recordView startForFilePath:[self fullPathAtCache:@"record.wav"]];
    
}
- (NSString *)fullPathAtCache:(NSString *)fileName{
    NSError *error;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (YES != [fm fileExistsAtPath:path]) {
        if (YES != [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
            NSLog(@"create dir path=%@, error=%@", path, error);
        }
    }
    return [path stringByAppendingPathComponent:fileName];
}
- (void)recordArcView:(FXRecordArcView *)arcView voiceRecorded:(NSString *)recordPath length:(float)recordLength{
    [self.helddownButton setTitle:@"语音评论" forState:UIControlStateNormal];
    self.textFeild.text = @"[语音评论]";
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message: @"录音完成" delegate: nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    //    [alert show];
    
}
-(void)LongPress{
    [self.recordView commitRecording];
    recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"record.wav"]];
    NSLog(@"%@",recordUrl);
}

-(void)addData{
    if (DX_int == 1) {
        NSString *poststr =[NSString stringWithFormat:@"message_id=%@&pg=%d",app.appmessageid,DX_pageNumber];
        [self londingPath:dxcommentURL Str:poststr];
    }else{
        NSString *poststr =[NSString stringWithFormat:@"message_id=%@&pg=%d",app.appmessageid,pageNumber];
        [self londingPath:allCommentURL Str:poststr];
    }
}


- (void)refreshViewDidLoading:(id)view
{
    if ([view isEqual:self.tableView.footer]) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            
            if (commentArray2.count >= [allCommentArray[allCommentArray.count-1] intValue]) {
                
                [self.tableView.footer setIsLastPage:YES];
                [self.tableView reloadData];
            } else {
                if (DX_int == 1) {
                    ++DX_pageNumber;
                }else{
                    ++pageNumber;
                }
                [self addData];
                [self.tableView.footer setState:RefreshViewStateDefault];
                [self.tableView reloadData];
                }
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - 请求加载帖子详情信息
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        allCommentArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:allCommentArray waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    
    if (sender == NULL) {
        self.comment_Count.text = @"0";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示：" message:@"该帖子目前没有新评论哟！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
    
    for (int i = 0; i <sender.count-1; i++) {
        Comment *co = [[Comment alloc]init];
        co.comment_content = sender[i][@"comment_content"];
        co.comment_time = sender[i][@"comment_time"];
        co.comment_heardPortrait = sender[i][@"comment_headPortrait"];
        co.comment_identifier = sender[i][@"comment_identifier"];
        co.user_phone = sender[i][@"user_phone"];
        co.comment_image = sender[i][@"comment_image"];
        co.comment_image = sender[i][@"comment_image"];
        co.comment_audio = sender[i][@"comment_audio"];
        [commentArray2 addObject:co];
        }
        
    }
    
    self.comment_Count.text = [NSString stringWithFormat:@"%d",[allCommentArray[allCommentArray.count-1] intValue]];
    
    [self.tableView reloadData];

}

#pragma mark - 返回tableview的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
        return commentArray2.count;
    

}

#pragma mark - 返回tableview的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return 1  + size.height;
    

}

#pragma mark - cell的内容加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib=[UINib nibWithNibName:@"commCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"commCell"];
    
    static NSString *cellIdentifier=@"commCell";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    Comment *comm = commentArray2[indexPath.row];
    cell.comment_Time.text=[NSString stringWithFormat:@"%@",comm.comment_time];
    
    cellContent = [NSString stringWithFormat:@"%@",comm.comment_content];
    
    strIdentifier=[NSString stringWithFormat:@"%@",comm.comment_identifier];
    
    //把手机号码的中间五位换成 *
    NSString *star=[comm.user_phone stringByReplacingCharactersInRange:NSMakeRange(3, 5) withString:@"***"];
    cell.user_phone.text = [NSString stringWithFormat:@"%@",star];
    
    
    if ([strIdentifier isEqualToString:@"0"]) {
        
        if ([cellContent rangeOfString:@"[图片评论]"].location !=NSNotFound) {
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",comm.comment_image]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            cell.image = image;
            ImageCompression *ima = [[ImageCompression alloc]init];
            [ima OriginImage:image scaleToSize:CGSizeMake(30, 30)];
            // 1> 生成文本附件
            NSTextAttachment *textAttach = [[NSTextAttachment alloc] init];
            textAttach.image = ima.scaledImage;
            
            // 2> 使用文本附件创建属性文本
            NSAttributedString *strA = [NSAttributedString attributedStringWithAttachment:textAttach];
            
            cell.comment_Content.attributedText = strA;
            cell.tagStr = @"1";
            
        }else if([comm.comment_content rangeOfString:@"[语音评论]"].location !=NSNotFound) {
            cell.audiourl = [NSURL URLWithString:comm.comment_audio];
            cell.audioview.hidden = NO;
            cell.comment_Content.hidden = YES;
            cell.comment_Content.userInteractionEnabled = NO;
        }else{
            cell.comment_Content.userInteractionEnabled = NO;
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            cell.comment_Content.text=[NSString stringWithFormat:@"%@",comm.comment_content];
        }
    }
    else{
        //部分字体变颜色
        NSRange range1=[cellContent rangeOfString:@":"];
        NSString *str1 = [cellContent substringWithRange:NSMakeRange(0, range1.location+1)];
        
        NSMutableAttributedString *colorStr1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",str1]];
        [colorStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range1.location+1)];//长度
        NSMutableAttributedString *colorStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",cellContent]];
        NSRange range=[cellContent rangeOfString:@":"];
        [colorStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range.location+1)];//长度
        
        
        
        if ([cellContent rangeOfString:@"[图片评论]"].location !=NSNotFound) {
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",comm.comment_image]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            cell.image = image;
            ImageCompression *ima = [[ImageCompression alloc]init];
            [ima OriginImage:image scaleToSize:CGSizeMake(30, 30)];
            // 1> 生成文本附件
            NSTextAttachment *textAttach = [[NSTextAttachment alloc] init];
            textAttach.image = ima.scaledImage;
            
            // 2> 使用文本附件创建属性文本
            NSAttributedString *strA = [NSAttributedString attributedStringWithAttachment:textAttach];
            
            [colorStr1 appendAttributedString:strA];
            
            cell.comment_Content.attributedText = colorStr1;
            
            cell.tagStr = @"1";
            
        }else if ([comm.comment_content rangeOfString:@"[语音评论]"].location !=NSNotFound) {
            cell.comment_Content.userInteractionEnabled = NO;
            cell.audiourl = [NSURL URLWithString:comm.comment_audio];
            cell.audioview.hidden = NO;
            cell.comment_Content.hidden = YES;
        }else{
            cell.comment_Content.userInteractionEnabled = NO;
            cell.audioview.hidden = YES;
            cell.comment_Content.hidden = NO;
            cell.comment_Content.attributedText = colorStr;
        }
        
    }
    
    NSURL *url = [NSURL URLWithString:comm.comment_heardPortrait];
    cell.HeadPortrait.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    
    cell.floor.text=[NSString stringWithFormat:@"%ld",(unsigned long)indexPath.row+1];
    
    
    return cell;
}
#pragma mark - 评论内容的所在cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    indexP = indexPath;
    
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }else{
        
        NSString *hf = @"回复";
        NSString *l = @"楼:";
        contentStr = [NSString stringWithFormat:@"%@%ld%@",hf,(unsigned long)indexPath.row+1,l];
        strIdentifier1 = @"1";
        self.textFeild.placeholder = [NSString stringWithFormat:@"%@",contentStr];
        self.CancelButton.hidden = NO;
        [self.CancelButton addTarget:self action:@selector(CancelClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self.textFeild resignFirstResponder];
    }
}

#pragma mark - 取消回复
-(void)CancelClick{
    self.CancelButton.hidden = YES;
    strIdentifier1 = @"0";
    self.textFeild.placeholder = @"";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"您已取消回复" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self.tableView deselectRowAtIndexPath:indexP animated:YES];
    
}

- (IBAction)takePhoto:(id)sender {
    if ([newviewStr isEqualToString:@"0"]) {
        self.newview.hidden = NO;
        newviewStr = @"1";
    }else{
        self.newview.hidden = YES;
        newviewStr = @"0";
    }
}

-(void)photoChoose{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择文件来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"本地相册",nil];
    [actionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://照相机
        {   if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"没有相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
            
        }
            break;
            
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            break;
            
        default:
            break;
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.textFeild.text=@"[图片评论]";
    img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.textFeild resignFirstResponder];
    self.textFeild.enabled = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)csImage:(UIImage *)image {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    
    ImageCompression *imageC = [[ImageCompression alloc]init];
    [imageC imageByScalingToMaxSize:image];
    [UIImageJPEGRepresentation(imageC.newimage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *Image=[UIImage imageWithContentsOfFile:imageFilePath];//写入文件
    self.photoImage=Image;
    
    NSData *data = UIImageJPEGRepresentation(self.photoImage, 0.5);
    NSURL *url=[NSURL URLWithString:commentImageURL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self;
    [request setData:data  withFileName:@"tmp.jpg" andContentType:@"image/jpg" forKey:@"comment_image"];
    [request setPostValue:commentID forKey:@"comment_id"];
    [request setTag:3];
    [request startAsynchronous];
}
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
    NSString *str1=dic[@"key"];
    
    if ([str1 isEqualToString:@"success"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"touxiangAPI" object:nil];
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 发送 按钮事件
- (IBAction)sendAction:(id)sender {
    
    self.textFeild.enabled = YES;
    [self.textFeild resignFirstResponder];
    
    //获取当前时间
    [self getTime];
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }
    else{
        if ([self.textFeild.text isEqualToString:@""]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入评论内容" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
            [alert show];
        }
        else{
            if ([strIdentifier1 isEqualToString:@"1"]) {
                Content = [NSString stringWithFormat:@"%@%@",contentStr,self.textFeild.text];
                NSString *poststr =[NSString stringWithFormat:@"user_phone=%@&message_id=%@&comment_content=%@&comment_time=%@&comment_headPortrait=%@&comment_identifier=%@",app.appPersonArray[0][@"user_phone"],app.appmessageid,Content,currentTime,app.appPersonArray[0][@"user_headPortrait"],strIdentifier1];
                [self loadingPath2:commentURL Str2:poststr];
                
                strIdentifier1 = @"0";
                NSString *poststr1 =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
                //评论数 +1
                [self londingPath1:commentcountURL Str1:poststr1];
                self.textFeild.text = @"";
                [self hide];
            }
            else{
                NSString *poststr1 =[NSString stringWithFormat:@"user_phone=%@&message_id=%@&comment_content=%@&comment_time=%@&comment_headPortrait=%@&comment_identifier=%@",app.appPersonArray[0][@"user_phone"],app.appmessageid,self.textFeild.text,currentTime,app.appPersonArray[0][@"user_headPortrait"],strIdentifier1];
                
                //评论请求
                [self loadingPath2:commentURL Str2:poststr1];
                if ([self.textFeild.text isEqualToString:@"图片评论"]) {
                    [self performSelector:@selector(csImage:)  withObject:img afterDelay:0.5];
                }
                strIdentifier1 = @"0";
                NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
                
                //评论数 +1
                [self londingPath1:commentcountURL Str1:poststr];
                self.textFeild.text = @"";
                [self hide];
            }
        }
    }
    self.textFeild.placeholder = @"";
}

#pragma mark - 评论数量＋1
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commcount = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:commcount waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
}

#pragma mark - "评论"请求数据加载
-(void)loadingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commentstr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshDatacomment:) withObject:commentstr waitUntilDone:YES];
    }];
}
-(void)refreshDatacomment:(NSMutableArray *)sender{
    for (NSDictionary *dic1 in commentstr){
        c = [[Comment alloc]init];
        commentID = dic1[@"comment_id"];
        c.comment_content = dic1[@"comment_content"];
        c.comment_time = dic1[@"comment_time"];
        c.comment_heardPortrait = dic1[@"comment_heardPortrait"];
        c.comment_identifier=dic1[@"comment_identifier"];
        c.user_phone = dic1[@"user_phone"];
        c.comment_image = dic1[@"comment_image"];
        c.comment_audio = dic1[@"comment_audio"];
        [commentArray2 addObject:c];
    }
    if ([c.comment_content rangeOfString:@"[图片评论]"].location !=NSNotFound) {
        [self performSelector:@selector(csImage:)  withObject:img afterDelay:0.5];
    }
    if ([self.helddownButton.titleLabel.text isEqualToString:@"语音评论"]) {
        [self audioupload];
    }
    showTimeStr = [ NSString stringWithFormat:@"%d",([app.showTime intValue]+1)];
    app.showTime = showTimeStr;
    [self.tableView reloadData];
}
-(void)audioupload{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[self fullPathAtCache:@"record.wav"]]];
    NSURL *url = [[NSURL alloc]initWithString:audioURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request addData:data withFileName:@"record.wav" andContentType:@"audio/wav" forKey:@"audio_path"];
    //添加普通的请求参数
    [request setPostValue:commentID forKey:@"comment_id"];
    [request setDelegate:self];
    [request startAsynchronous];
    self.helddownButton.hidden = YES;
    self.QXButton.hidden = YES;
    self.jiaButton.hidden = NO;
    newviewStr = @"0";
}

#pragma mark - 获取当前时间
-(void)getTime{
    NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
    currentTime=nowTime;
}

- (void) changeContentViewPoint:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    keyboard = keyboardRect.size.height;
    //    CGFloat keyBoardEndY = value.CGRectValue.origin.y;  // 得到键盘弹出后的键盘视图所在y坐标
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(change:) object:nil];
    [thread start];
    //添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
    }];
}
-(void)change:(id)sender
{
    //线程睡眠0.2秒以实现视图延迟上弹
    [NSThread sleepForTimeInterval:0.3];
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, -keyboard);
    //使视图使用这个变换
    self.view.transform = pTransform;
    
}
- (void)keyboardWillHide:(NSNotification *)notif {
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
    //使视图使用这个变换
    self.view.transform = pTransform;
    [UIView commitAnimations];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self hide];
}
-(void)hide{
    [self.textFeild endEditing:YES];
}

#pragma mark - 点击换行完成编辑
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (self.textFeild== textField) {
        [self.textFeild resignFirstResponder];
    }
    return YES;
    
}

#pragma mark - 倒叙按钮事件
- (IBAction)dxcomment:(id)sender {
    allCommentArray = [NSMutableArray array];
    commentArray2 = [NSMutableArray array];
    if (DX_int == 0) {
        DX_int = 1;
        DX_pageNumber = 1;
        [self addData];
        
    }else{
        DX_int = 0 ;
        pageNumber = 1;
        [self addData];
        
    }
    
}

- (IBAction)pic:(id)sender {
    self.newview.hidden = YES;
    [self photoChoose];
}

- (IBAction)audio:(id)sender {
    self.newview.hidden = YES;
    self.helddownButton.hidden = NO;
    self.QXButton.hidden = NO;
    self.jiaButton.hidden = YES;
}
- (IBAction)QX:(id)sender {
    [self.helddownButton setTitle:@"按住说话" forState:UIControlStateNormal];
    self.helddownButton.hidden = YES;
    self.jiaButton.hidden = NO;
    self.QXButton.hidden = YES;
    newviewStr = @"0";
}
@end
